package com.cq.androidtools.recycleview.table2

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cq.androidtools.R


/**
 * 作者: CQ
 * 日期: 2021-08-13
 * 说明:
 */
class RecyclerViewContent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0,
) : RecyclerView(context, attrs, defStyleAttr) {

    var mDivider: Drawable = ContextCompat.getDrawable(context, R.drawable.shap_button_select_white)!!

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        super.onMeasure(widthSpec, heightSpec)
        if (getChildAt(0) == null) {
            return
        }
        val gridLayoutManager = layoutManager as GridLayoutManager
        val ww = adapter!!.itemCount / gridLayoutManager.spanCount

        val widthChild = getChildAt(0).width + getChildAt(0).paddingLeft + getChildAt(0).paddingRight + mDivider.intrinsicWidth
        val widthChildAll = widthChild * ww

        val heightChild = getChildAt(0).height + getChildAt(0).paddingTop + getChildAt(0).paddingBottom + mDivider.intrinsicHeight
        val heightAll = gridLayoutManager.spanCount * heightChild
        Log.e("RecyclerViewContent", "h = $widthChildAll ; w = $heightAll")
        setMeasuredDimension(widthChildAll, heightAll)
    }

    override fun scrollTo(x: Int, y: Int) {
        super.scrollTo(x, y)
        val clazz = this.javaClass.superclass.superclass.superclass
        val oldX: Int = scrollX
        val oldY: Int = scrollY
        val mScrollX = clazz.getDeclaredField("mScrollX")
        mScrollX.isAccessible = true
        mScrollX.set(this, x)

        val mScrollY = clazz.getDeclaredField("mScrollY")
        mScrollY.isAccessible = true
        mScrollY.set(this, y)
        onScrollChanged(x, y, oldX, oldY)
        if (!awakenScrollBars()) {
            postInvalidateOnAnimation()
        }
    }
}